import React, { useState } from 'react';
import { request, useRequest } from 'ice';
import {
  Card,
  Table,
  Pagination,
  Divider,
  ResponsiveGrid,
  Button,
  Box,
  Form,
  Field,
  Loading,
  Dialog,
  DatePicker,
  Message,
  Tag,
  Balloon,
} from '@alifd/next';
import moment from 'moment';
import { DialogProps } from '@alifd/next/types/dialog';

import styles from './index.module.scss';

moment.locale('zh-cn');

export type CastType = 'image' | 'video';

export interface CastProps {
  type: CastType | undefined;
  screenId: string | undefined;
}

const DialogCast: React.FC<CastProps & DialogProps> = (props) => {
  const { type, screenId, onClose, ...lastProps } = props;
  const limit = 5;
  const [page, setPage] = useState(1);
  const [sort, setSort] = useState({
    field: 'date',
    order: 'desc',
  });
  const [filter, setFilter] = useState({});
  const field = Field.useField({ autoUnmount: false });
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  const { data, loading, request: cRequest } = useRequest(
    () =>
      type && screenId
        ? {
            url: '/api/schedule',
            params: {
              type,
              screenId,
              limit,
              skip: (page - 1) * limit,
              ...filter,
              ...sort,
            },
          }
        : Promise.resolve({ total: 0, items: [] }),
    {
      manual: false,
      refreshDeps: [type, screenId, page, sort, filter],
    },
  );

  const onDelete = (_ids: string[]) => {
    return () => {
      Dialog.confirm({
        title: '删除提醒',
        content: `确定要删除 ${_ids.length} 天的投放吗？`,
        onOk: async () => {
          try {
            await request.delete('/api/schedule', { data: { type, _ids } });
            cRequest();
            Message.success('删除成功');
          } catch (e) {
            Message.error('网络错误');
          }
        },
      });
    };
  };

  return (
    <Dialog
      shouldUpdatePosition
      isFullScreen
      style={{ width: 1000 }}
      footerActions={[]}
      closeable={true}
      onClose={() => {
        setPage(1);
        onClose();
      }}
      {...lastProps}
    >
      <Card free>
        <Card.Content>
          <Box padding={10}>
            <Form responsive fullWidth labelAlign="top" field={field}>
              <Form.Item colSpan={6} label="日期">
                <DatePicker.RangePicker {...field.init('dateRange')} />
              </Form.Item>
              <ResponsiveGrid.Cell colSpan={3} className={styles.btns}>
                <Box spacing={8} direction="row" align="flex-end" justify="center" style={{ height: '100%' }}>
                  <Button
                    type="primary"
                    onClick={() => {
                      const { dateRange } = field.getValues();
                      const filter = {
                        startDate: dateRange && dateRange[0] && dateRange[0].format('YYYY-MM-DD'),
                        endDate: dateRange && dateRange[1] && dateRange[1].format('YYYY-MM-DD'),
                      };
                      setPage(1);
                      setFilter(filter);
                    }}
                  >
                    查询
                  </Button>
                  <Form.Reset>重置</Form.Reset>
                </Box>
              </ResponsiveGrid.Cell>
            </Form>
          </Box>
          <Divider dashed />
          <div className={styles.Main}>
            <Loading visible={loading} style={{ display: 'block' }}>
              <div className={styles.add}>
                <Button type="primary" disabled={!selectedIds.length} onClick={onDelete(selectedIds)}>
                  删除
                </Button>
              </div>
              <Table
                className={styles.Table}
                hasBorder={false}
                dataSource={data?.items}
                primaryKey="_id"
                rowSelection={{
                  selectedRowKeys: selectedIds,
                  columnProps: () => ({ lock: 'left' }),
                  onChange: (ids) => {
                    setSelectedIds(ids);
                  },
                }}
                sort={{ [sort.field]: sort.order }}
                onSort={(field, order) => {
                  setPage(1);
                  setSort({ field, order });
                }}
              >
                <Table.Column title="日期" dataIndex="date" sortable width={150} />
                <Table.Column
                  title={`已投放${type === 'video' ? '视频' : '图片'}`}
                  dataIndex="resources"
                  cell={(arr: any[], _i: number, r: any) => (
                    <Tag.Group>
                      {arr.map((v: any, i: number) => {
                        const tag = (
                          <Tag.Closeable
                            onClose={() => {
                              Dialog.confirm({
                                title: '删除提醒',
                                content: `确定要删除这个${type === 'video' ? '视频' : '图片'}投放吗？`,
                                onOk: async () => {
                                  try {
                                    const resources = arr.slice(0);
                                    resources.splice(i, 1);
                                    await request.put(`/api/schedule/${r._id}`, { type, resources });
                                    cRequest();
                                    Message.success('删除成功');
                                  } catch (e) {
                                    Message.error('网络错误');
                                  }
                                },
                              });
                              return false;
                            }}
                          >
                            {v.name}
                          </Tag.Closeable>
                        );
                        if (type === 'image') {
                          return (
                            <Balloon key={i} trigger={tag} triggerType="click" closable={false}>
                              <img style={{ height: 150 }} src={v.url} />
                            </Balloon>
                          );
                        } else {
                          return (
                            <a key={i} href={v.url} target="_blank">
                              {tag}
                            </a>
                          );
                        }
                      })}
                    </Tag.Group>
                  )}
                />
              </Table>
              <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                <div className={styles.total}>共 {data?.total} 个投放</div>
                <Pagination current={page} pageSize={limit} total={data?.total} onChange={(cur) => setPage(cur)} />
              </Box>
            </Loading>
          </div>
        </Card.Content>
      </Card>
    </Dialog>
  );
};

export default DialogCast;
